package fun.xinnix.handler;

import cn.hutool.core.collection.CollectionUtil;
import fun.xinnix.entity.Result;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.ValidationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Set;

@RestControllerAdvice
public class GlobalException {
    @ExceptionHandler(ConstraintViolationException.class)
    public Result constraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        String message = e.getMessage();
        if (CollectionUtil.isNotEmpty(constraintViolations)) {
            ConstraintViolation<?> next = constraintViolations.iterator().next();
            message = next.getMessage();
        }
        return Result.error(message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValid(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        String message = e.getMessage();
        if (CollectionUtil.isNotEmpty(allErrors)) {
            message = allErrors.get(0).getDefaultMessage();
        }
        return Result.error(message);
    }

    @ExceptionHandler(ValidationException.class)
    public Result validation(ValidationException e) {
        return Result.error(e.getMessage());
    }
}